<?php

namespace App\Http\Exports;

use App\Library\NoNumericValueBinder;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Log;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class OrderExport
{
    protected $name;
    protected $data;
    protected $spreadsheet;

    public function __construct(string $name, array $data)
    {
        $this->name = $name;
        $this->data = $data;
        $this->spreadsheet = new Spreadsheet();
    }

    public function getTitle()
    {
        return [
            "订单id",
            "下单时间",
            "订单金额",
            "姓名",
            "电话",
            "推荐人",
            "支付状态",
            "商品",
            "付款信息"
        ];
    }

    public function downLoad()
    {
        $tmp = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'k', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        $title = $this->getTitle();
        $colCount = count($this->getTitle());
        $col = $tmp[$colCount-1];
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $data = $this->data;
        $worksheet->getStyle("A1:{$col}1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFFAF0');
        $worksheet->getStyle("A:{$col}")->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
        array_unshift($data, $title);
        foreach ($data as $key => $value) {
            $key += 1;
            $worksheet->getCell("{$col}".$key)->setValueBinder(new NoNumericValueBinder());
        }
        $worksheet->fromArray($data, null);

        $xLsx = new Xlsx($spreadsheet);
        $tempName = tempnam(sys_get_temp_dir(), "export-");
        $xLsx->save($tempName);
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        return response()->download(
            $tempName,
            $this->name
        )->deleteFileAfterSend(true);
    }
}
